package com.puboot.common.config;

/**
 * @author Leonidax
 * @date 2024/10/10 14:21
 * @description LocaleConfig
 */
import com.puboot.component.ComicCookeLocaleResolver;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;

@Configuration
public class LocaleConfig implements WebMvcConfigurer {

    // 配置 LocaleResolver，设置默认语言为英文
    @Bean
    public LocaleResolver localeResolver() {
        ComicCookeLocaleResolver resolver = new ComicCookeLocaleResolver();
        resolver.setDefaultLocale(resolver.defaultLanguage); // 默认语言
        resolver.setCookieName("comic.lang");
        resolver.setCookieMaxAge(86400000);
        return resolver;
    }

    // 配置 LocaleChangeInterceptor，用于拦截请求中的 'lang' 参数并切换语言
    @Bean
    public LocaleChangeInterceptor localeChangeInterceptor() {
        LocaleChangeInterceptor interceptor = new LocaleChangeInterceptor();
        interceptor.setParamName("lang"); // 'lang' 参数用于切换语言
        return interceptor;
    }

    // 将 LocaleChangeInterceptor 注册到拦截器中
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(localeChangeInterceptor());
    }
}
